#include <iostream>
#include <vector>
#include <list>
#include <cmath>

#include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <TH1D.h>
#include <TCanvas.h>
#include <TVector3.h>

#include "GeomSvc.h"
#include "TriggerRoad.h"
#include "TriggerAnalyzer.h"

using namespace std;

int main(int argc, char* argv[])
{
  GeomSvc* p_geomSvc = GeomSvc::instance();
  p_geomSvc->init("geometry_R962");

  int nHits;
  int detectorID[500];
  int elementID[500];
  double x[500], y[500];

  TFile* dataFile = new TFile(argv[1], "READ");
  TTree* dataTree = (TTree*)dataFile->Get("save");

  dataTree->SetBranchAddress("nHits", &nHits);
  dataTree->SetBranchAddress("detectorID", detectorID);
  dataTree->SetBranchAddress("elementID", elementID);
  dataTree->SetBranchAddress("x", x);
  dataTree->SetBranchAddress("y", y);

  int nHits_new;
  int detectorID_new[500];
  int elementID_new[500];
  double x_new[500], y_new[500];

  TFile* saveFile = new TFile(argv[2], "recreate");
  TTree* saveTree = dataTree->CloneTree(0);

  double cut = atof(argv[3]);
  for(int i = 0; i < dataTree->GetEntries(); i++)
    {
      dataTree->GetEntry(i);

      nHits_new = 0;
      for(int j = 0; j < nHits; j++)
	{
	  if((detectorID[j] == 31 || detectorID[j] == 32) && fabs(y[j]) < cut) continue;

	  detectorID_new[nHits_new] = detectorID[j];
	  elementID_new[nHits_new] = elementID[j];
	  x_new[nHits_new] = x[j];
	  y_new[nHits_new] = y[j];

	  ++nHits_new;
	}

      nHits = nHits_new;
      for(int j = 0; j < nHits_new; j++)
	{
	  detectorID[j] = detectorID_new[j];
	  elementID[j] = elementID_new[j];
	  x[j] = x_new[j];
	  y[j] = y_new[j];
	}

      saveTree->Fill();
    }

  saveFile->cd();
  saveTree->Write();
  saveFile->Close();

  return 1;
}
